import config from 'core/config'
import { makeMap, isNative } from '../util/index'

let initProxy

if (process.env.NODE_ENV !== 'production') {
  const allowedGlobals = makeMap(
    'Infinity,undefined,NaN,isFinite,isNaN,' +
    'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +
    'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,' +
    'require'
  )

  const hasProxy =
    typeof Proxy !== 'undefined' && isNative(Proxy)

  // 存在proxy时对按键设置代理  这个因为只涉及pc  所以直接拿Proxy
  if (hasProxy) {
    const isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta,exact')
    config.keyCodes = new Proxy(config.keyCodes, {
      set (target, key, value) {
        if (isBuiltInModifier(key)) {
          return false
        } else {
          target[key] = value
          return true
        }
      }
    })
  }

  const hasHandler = {
    has (target, key) {
      const has = key in target
      const isAllowed = allowedGlobals(key) ||
        (typeof key === 'string' && key.charAt(0) === '_' && !(key in target.$data))
      return has || !isAllowed
    }
  }

  const getHandler = {
    get (target, key) {
      return target[key]
    }
  }

  initProxy = function initProxy (vm) {
    if (hasProxy) {
      const options = vm.$options
      /**
       * 如果传入的options有render并且render中已经剥离了，直接获取操作
       * 否则返回布尔值，
       */
      const handlers = options.render && options.render._withStripped
        ? getHandler
        : hasHandler
      vm._renderProxy = new Proxy(vm, handlers)
    } else {
      vm._renderProxy = vm
    }
  }
}

export { initProxy }
